<template>
  <div class="login-root">
    <div id="particles-js" />
    <div class="container">
      <div class="drop">
        <div class="content">
          <h1>Sign In</h1>
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
            <div class="inputBox">
              <input v-model="loginForm.username" type="text" placeholder="Username">
            </div>
            <div class="inputBox">
              <input v-model="loginForm.password" type="password" placeholder="Password">
            </div>
            <div class="inputBox">
              <input type="submit" value="Login" @click="handleLogin">
            </div>
          </el-form>
        </div>
        <div>
          <a href="#" class="btns" aria-label="Forgot Password">Forget Password</a>
          <a href="#" class="btns signup" aria-label="Sign Up">Signup</a>
        </div>
      </div>
    </div>
    <div class="left-image">
      <img src="@/assets/robot.png" alt="left image">
    </div>
  </div>
</template>

<script>

/* global particlesJS */
import '@/styles/login-style.css'
import '@/assets/js/particles/particles.min.js'
import { validUsername } from '@/utils/validate'

export default {
  name: 'Login',
  components: { },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: '123456xc'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    this.initParticles()
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    initParticles() {
      particlesJS('particles-js', {
        'particles': {
          'number': { 'value': 60 },
          'color': { 'value': '#ffffff' },
          'shape': { 'type': 'circle' },
          'opacity': { 'value': 0.5 },
          'size': { 'value': 3, 'random': true },
          'line_linked': {
            'enable': true,
            'distance': 150,
            'color': '#ffffff'
          },
          'move': {
            'enable': true,
            'speed': 4,
            'direction': 'none', // 无固定方向，更自然
            'random': true,
            'out_mode': 'out' // 粒子超出容器后消失
          }
        },
        'interactivity': {
          'detect_on': 'canvas',
          'events': {
            'onhover': { 'enable': true, 'mode': 'grab' }, // 鼠标悬浮时粒子连线
            'onclick': { 'enable': true, 'mode': 'push' }, // 点击时新增粒子
            'resize': true // 窗口 resize 时自适应
          },
          'modes': {
            'grab': { 'distance': 140, 'line_linked': { 'opacity': 0.5 }},
            'push': { 'particles_nb': 4 } // 点击时新增4个粒子
          }
        },
        'retina_detect': true // 视网膜屏适配
      })
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>
